import { httpState, cancelTokenItem } from '~/types/http'
export const useHttp = defineStore({
  id: 'http',
  state: (): httpState => ({
    cancelTokenList: [],
    errRequestList: []
  }),
  actions: {
    addCancelToken(item: cancelTokenItem) {
      this.cancelTokenList.unshift(item)
    },
    cancelToken(itemName: string) {
      this.cancelTokenList = this.cancelTokenList.filter((item) => {
        const flag = item.name !== itemName
        !flag && item.cancel()
        return flag
      })
    },
    // 清空所有请求
    clearToken() {
      this.cancelTokenList.forEach((item) => {
        item.cancel()
      })
      this.cancelTokenList = []
    },
    delCancelToken(itemName: string) {
      this.cancelTokenList = this.cancelTokenList.filter((item) => {
        return item.name !== itemName
      })
    },
    addErrRequest(req) {
      const { data, config, status, response = {} } = req
      console.log('req', req, data)

      this.errRequestList.push({
        // requestId: data?.requestId ?? response?.data.requestId ?? 'null',
        status: status ?? data?.status ?? response?.status ?? '',
        code: data?.data?.code ?? data?.status ?? '',
        msg: data?.data?.message,
        // timestamp: data?.timestamp ?? response?.data?.timestamp: ,
        method: config.method,
        url: config.url,
        data: data ?? response?.data ?? 'null',
        config
      })
    },
    cleanErr() {
      this.errRequestList = []
      window['$message'].success('已清除！')
    }
  }
})
